#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>

#include "sample_comm_nnie.h"
#include "ai_infer_process.h"
#include "sample_media_ai.h"
#include<math.h>

#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif
#endif /* End of #ifdef __cplusplus */

#define MODEL_FILE_FACEREC     "/userdata/models/face_detect/Mobileface_mnet.wk" // mobileface framework wk model
#define PIRIOD_NUM_MAX     49 // Logs are printed when the number of targets is detected
#define DETECT_OBJ_MAX     32 // detect max obj

#define FEATURE_NUM     128
static uintptr_t g_faceModel = 0;

static HI_S32 MobileFaceRecLoad(uintptr_t* model)
{
    SAMPLE_SVP_NNIE_CFG_S *self = NULL;
    HI_S32 ret;

    ret = MobileFaceCreate(&self, MODEL_FILE_FACEREC);
    *model = ret < 0 ? 0 : (uintptr_t)self;
    SAMPLE_PRT("MobileFaceLoad ret:%d\n", ret);

    return ret;
}

HI_S32 FaceRecInit(void)
{
    return MobileFaceRecLoad(&g_faceModel);
}

static HI_S32 MobileFaceRecUnload(uintptr_t model)
{
    CnnFaceRecDestroy((SAMPLE_SVP_NNIE_CFG_S*)model);
    return 0;
}

HI_S32 FaceRecExit(void)
{
    return MobileFaceRecUnload(g_faceModel);
}



HI_S32 MobileFaceRecCal(uintptr_t model, IVE_IMAGE_S *img, float feature_buff[])
{
    SAMPLE_SVP_NNIE_CFG_S *self = (SAMPLE_SVP_NNIE_CFG_S*)model; // reference to SDK sample_comm_nnie.h Line 99

    HI_S32 ret;

    ret = MobileFaceCalImg(self, img,feature_buff); //推理
    SAMPLE_CHECK_EXPR_RET(ret < 0, "cnn cal FAIL, ret=%d\n", ret);
    /*
        处理结果
    */ 
    return ret;
}
HI_S32 FaceRecCal(IVE_IMAGE_S *img, float feature_buff[])
{
    int ret = MobileFaceRecCal(g_faceModel, img, feature_buff);
    return ret;
}
//计算人脸欧式距离
HI_FLOAT FaceRecDistance(float feature_buff[], float feature_to_compare[])
{   
   float dis = 0;
   for(int i=0; i<FEATURE_NUM; i++)
       dis+=(feature_buff[i]-feature_to_compare[i])*(feature_buff[i]-feature_to_compare[i]);
    dis = sqrt(dis);
    //printf("face_distance = %lf\n",dis);
    return dis;
}

//比较人脸
HI_S32 FaceRecCompare(float feature_buff[], float feature_to_compare[], float tolerance,float *dis)
{   
    *dis = FaceRecDistance(feature_buff,feature_to_compare);
    if(*dis <=  tolerance)
        return 1;
    else 
        return 0;
}
#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif /* End of #ifdef __cplusplus */
